<?php

class Wiki_Search_Controller extends Base_Controller
{

    public function action_tag($term)
    {
        $this->search($term);
    }

    public function action_category($term)
    {
        $this->search(null, $term);
    }

    public function action_entry($term)
    {
        $this->search(null, null, $term);
    }

    private function search($tag = null, $category = null, $entry = null)
    {
        $View = View::make("wiki::search.list");

        $entries = array();
        $tags = array();
        $categories = array();

        if ($tag != null) {
            $tags = $this->getTags($tag);
        }

        if ($categories != null) {
            $categories = $this->getCategories($category);
        }


        $View->entries = $entries;

        return $View;
    }

    private function getTags($tag)
    {
        if (is_numeric($tag)) {
            $Tags = Tag::where('language_id', '=', Language::getActive())->where('id', '=', $tag)->get();
            $Tag = current($Tags);

            if ($Tag)
                $tags[] = $Tag->id;
        }

        $Tags = Tag::where('language_id', '=', Language::getActive())->where('tag', 'like', '%' . $tag . '%')->get();
        foreach ($Tags as $Tag) {
            $tags[] = $Tag->id;
        }
        return $tags;
    }

    private function getCategories($category)
    {
        if (is_numeric($category)) {
            $Categories = Category::where('language_id', '=', Language::getActive())->where('id', '=', $category)->get();
            $Category = current($Categories);

            if ($Category)
                $categories[] = $Category->id;
        }

        $categories = Category::where('language_id', '=', Language::getActive())->where('category', 'like', '%' . $category . '%')->get();
        foreach ($Tags as $Tag) {
            $tags[] = $Tag->id;
        }
        return $tags;
    }

}